package com.hd.trans.files.repository;

import android.content.ContentResolver;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.MimeTypeMap;

import com.hd.trans.files.bean.Video;
import com.hd.trans.utils.StorageUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * Author: yangtianwen
 * Time: 2021/12/16
 * Des:
 */
public class LocalVideoProvider {

    public static final String TAG = "LocalVideoProvider";

    private static final int DEFAULT_SCAN = 1;
    private static final int FAST_SCAN = 2;
    public static final int CUSTOM_SCAN = 3;

    private static final String VIDEO_MINE = "video";

    private final File ROOT_SD_DIR;

    private boolean mCancel;

    // 最近一次扫描路径
    private String lastScanPath;
    private ContentResolver mContentResolver;

    private ScanFileInterface mScanFileInterface;

    /**
     * 扫描SD目录路径 天天动听允许更改下载目录，默认都在“/ttpod”下 QQ音乐播放器也允许改变，但是必须有多张SD卡
     * 百度音乐允许更改下载目录，到处都可以，使用默认路径 多米音乐播放器允许改变下载目录，但是必须有多张SD卡
     */
    private static final String[] DEFAULT_DIRECTORY = {"/ttpod/", "/qqmusic/",
            "/Baidu_music/", "/DUOMI/", "/kgmusic/"};

    public LocalVideoProvider() {
        ROOT_SD_DIR = new File(StorageUtils.getStorageDirectory());
    }

    /**
     * 通过路径扫描本地视频
     */
    public List<Video> searchVideo(List<String> scanDirectory, String keyWord) {
        List<Video> videos = new ArrayList<>();
        for (int i = 0; i < scanDirectory.size(); i++) {
            if (mCancel) {
                break;
            }
            try {
                File file = new File(scanDirectory.get(i)).getCanonicalFile();
                if (isFilterDirectoryOrFile(file.getAbsolutePath()) || file.getAbsolutePath().equals(lastScanPath) ||
                        (ROOT_SD_DIR.getParentFile().equals(file.getParentFile()) && !ROOT_SD_DIR.equals(file))) {
                    continue;
                }
                lastScanPath = file.getAbsolutePath();
                scanFile(videos, file, keyWord);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (mScanFileInterface != null) {
            mScanFileInterface.scanNewFileNum(videos.size());
        }
        return videos;
    }


    /**
     * 过滤文件
     */
    private boolean isFilterDirectoryOrFile(String name) {
        return name.contains(StorageUtils.getStorageDirectory() + "data/") || name.contains("/sys/");
    }

    /**
     * 扫描音乐文件
     */
    private void scanFile(List<Video> videos, File file, String text) {
        if (!file.exists() || mCancel) {
            return;
        }
        // 判断是否是一个标准的文件,
        if (file.isFile() && !file.isHidden()) {
            String extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString());
            String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            String path = null;
            try {
                path = file.getCanonicalPath().toLowerCase(Locale.getDefault());
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (mScanFileInterface != null) {
                mScanFileInterface.scanFilePath(path);
            }
            if (mime == null || !mime.contains(VIDEO_MINE)) {
                // 不是视频
                return;
            }
            if (isMusicAvaliable(path) && !file.getName().isEmpty()) {
                if (file.getName().toLowerCase().contains(text.toLowerCase())) {
                    Video video = new Video(0, file.getName(), file.getPath(), file.lastModified() * 1000, 0, file.length());
                    video.setName(file.getName());
                    video.setPath(file.getPath());
//                    video.setSize(file.length());
                    video.setIsDirectory(false);
                    video.setDate(file.lastModified() * 1000);
                    videos.add(video);
                }
            }
        } else if (file.isDirectory()) {
            // 文件夹，获取当前文件夹的文件
            File[] files = file.listFiles();
            if (files != null) {
                for (File value : files) {
                    if (mCancel) {
                        return;
                    }
                    if (isFilterDirectoryOrFile(value.getAbsolutePath().toLowerCase())
                            || (ROOT_SD_DIR.getParentFile().equals(value.getParentFile()) && !ROOT_SD_DIR.equals(value))) {
                        continue;
                    }
                    try {
                        File nextFile = new File(value.getCanonicalPath());
                        if (nextFile.getAbsolutePath().equals(lastScanPath)) {
                            continue;
                        }
                        lastScanPath = nextFile.getAbsolutePath();
                        if (file != nextFile) {
                            scanFile(videos, nextFile, text);
                        }
                    } catch (IOException e) {
                        Log.w(TAG, "扫描路径异常：" + e.getMessage());
                    }
                }
            }
        }
    }


    /**
     * 音乐文件是否可用
     */
    private boolean isMusicAvaliable(String path) {
        if (!TextUtils.isEmpty(path)) {
            File file = new File(path);
            return file.exists();
        } else {
            return false;
        }
    }

    public void setScanFileInterface(ScanFileInterface scanFileInterface) {
        this.mScanFileInterface = scanFileInterface;
    }

    /**
     * 定义扫描文件路径的接口
     */
    public interface ScanFileInterface {
        /**
         * 返回扫描文件路径
         *
         * @param path
         */
        public void scanFilePath(String path);

        /**
         * 返回扫描文件的新增条数
         *
         * @param newNum
         */
        public void scanNewFileNum(int newNum);
    }
}
